package com.elvt.server.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.elvt.server.mapper.MenuMapper;
import com.elvt.server.pojo.Admin;
import com.elvt.server.pojo.Menu;
import com.elvt.server.service.IMenuService;
import com.elvt.server.utils.AdminUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 作者：elvt
 * @since 2022-05-21
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据用户id查询菜单
     * @return
     */
    @Override
    public List<Menu> getMenusByAdmin() {
        Integer adminId = AdminUtil.getCurrentAdmin().getId();
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();

        //从redis数据库里面查询到数据
        List<Menu> menus = (List<Menu>) valueOperations.get("ybg:menu_" + adminId);
        //判断是否为空，如果为空，从mysql查询数据

        if (null==menus||CollectionUtils.isEmpty(menus) &&  menus.size()==0){
            System.out.println("1111");
           menus= menuMapper.getMenuByAdminId(adminId);
           //将数据库设置到redis中
           valueOperations.set("ybg:menu_"+adminId,menus);
        }
        return menus;

    }

    @Override
    public List<Menu> findMenusByRole() {
        return menuMapper.getRoleByMenuId();
    }


}
